<?php
namespace App\Module\Admin\Service;

use App\Constants\Constant;
use App\Model\UserScore;
use App\Model\UserScoreDetail;
use App\Module\Admin\Request\Score\DecreaseRequest;
use Hyperf\DbConnection\Db;

class ScoreService {

    public function search($user_id,$origin,$pagesize){
        $query = UserScoreDetail::query()->latest("add_time")->with("user");

        if(!empty($user_id)){
            $query->where("user_id",$user_id);
        }
        if(!empty($origin)){
            $query->where("origin",$origin);
        }

        return $query->paginate($pagesize);
    }

    public function decrease(DecreaseRequest $request){
        return Db::transaction(function () use($request){
            $score = UserScore::query()->findOrFail($request->input("user_id"));
            $score->setAttribute("available",$score->getAttribute("available") - $request->input("score"));
            $score->setAttribute("consume",$score->getAttribute("consume") + $request->input("score"));
            $score->save();

            $score_detail = new UserScoreDetail();
            $score_detail->setAttribute("user_id",$request->input("user_id"));
            $score_detail->setAttribute("direction",Constant::DIRECTION_DEC);
            $score_detail->setAttribute("score",$request->input("score"));
            $score_detail->setAttribute("remark","管理员扣除");
            $score_detail->save();
        });
    }
}